package model.xml;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.SQLXML;

import model.configuration.ConfigData;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;


public class SerializeObject {

	private static final Logger localLoger = LogManager.getLogger(SerializeObject.class.getClass());
	
	private static final String targetEncoding = "UTF8";
	private static final Format xmlFormat = new Format(ConfigData.XML_HEAD_UTF8); // надо допиливать распарсинг в базе
	//private static final Format xmlFormat = new Format();
	
	public static String serializeToString(Object object) throws Exception {
		localLoger.trace(ConfigData.METHOD_START_TEXT);
		String result = null;
		Serializer serializer = new Persister(xmlFormat); 							//shamanism
		//Need For Stream
		OutputStream outStream = new ByteArrayOutputStream();				
		OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, targetEncoding); 
		serializer.write(object, outStreamWriter);							//shamanism create XML from object and put it to stream. Powerfull magic
		//Mahalai bahalai stream to string prevrashai
		result = outStreamWriter.toString();
		localLoger.debug(outStream.toString());
		localLoger.trace(ConfigData.METHOD_END_TEXT);
		return outStream.toString(); 
	}
	
	public static OutputStream serializeToOutputStream(Object object) throws Exception {
		localLoger.trace(ConfigData.METHOD_START_TEXT);
		Serializer serializer = new Persister(xmlFormat);
		OutputStream outByteStream = new ByteArrayOutputStream();
		OutputStreamWriter result = new OutputStreamWriter(outByteStream, targetEncoding);
		serializer.write(object, result);
		localLoger.debug(outByteStream.toString());
		localLoger.trace(ConfigData.METHOD_END_TEXT);
		return outByteStream;
	}
	
	public static Object deSerializeFromXml(Class pClass, SQLXML sqlxml) throws Exception {
		Object result = null;
		localLoger.trace(ConfigData.METHOD_START_TEXT);
		Serializer serializer = new Persister(xmlFormat);
		InputStream binaryStream = sqlxml.getBinaryStream();
		result = serializer.read(pClass, binaryStream);
		localLoger.trace(ConfigData.METHOD_END_TEXT);
		return result;
	}
	
	public static Object deSerializeFromString(Class pClass, String string) throws Exception {
		Serializer serializer = new Persister(xmlFormat);
		return serializer.read(pClass, string);
	}
	
}
